package org.springframework.samples.mvc.ajax.account;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.bazaarvoice.prr.util.BazaarvoiceUtils;

@Controller
@RequestMapping(value = "/oldiframe")
public class OldIframeController {

	@RequestMapping(method = RequestMethod.GET)
	public String getCreateForm(Model model) {
		return "oldiframe/oldiframe";
	}

	@RequestMapping(value = "/submissionPage.html", method = RequestMethod.GET)
	public String getAccounts(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "bvauthenticateuser") String bvauthenticateuser,
			Model model) {
		List<Cookie> cookies = new ArrayList<Cookie>(Arrays.asList(request
				.getCookies()));
		Boolean loggedIn = false;
		for (Cookie cookie : cookies) {
			if (cookie.getName().equals("loggedIn")) {
				loggedIn = Boolean.valueOf(cookie.getValue());
				break;
			}
		}
		if (Boolean.valueOf(bvauthenticateuser) == true && !loggedIn) {
			return "redirect:/login?" + request.getQueryString();
		} else {
			String user = "";
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("userId")) {
					user += cookie.getValue();
					break;
				}
			}
			user += "&emailaddress=sample@gmail.com";
			String userId = BazaarvoiceUtils.encodeUserID(user, "6efCdrsDTZySakHD1Q5qnHjmJZgaToD8OEIwqdqeJNzCjP2Kg9i9jjzwpG2Mmv");
			model.addAttribute("userId", userId);
			return "oldiframe/submission";
		}

	}
}
